package com.py.framework.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.framework.common.Constants;
import com.py.framework.common.controller.SystemController;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.helper.HttpServletHelper;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.rest.support.RestServiceResult;
import com.py.framework.entity.UserEntity;
import com.py.framework.entity.WorkFlowRole;
import com.py.framework.service.AuthenticationService;
import com.py.framework.service.WorkFlowRoleService;

/**
 * 工作流角色管理Controller
 * 
 * @author Leegern
 * @date 2018年5月23日
 */
@RestController
@RequestMapping("/wfrole")
public class WorkFlowRoleController extends SystemController {

	@Autowired
	private WorkFlowRoleService workFlowRoleService;

	@Autowired
	private AuthenticationService authenticationService;

	/**
	 * @api {post} /wfrole/addWorkFlowRole.json 添加工作角色实体
	 * @apiName addWorkFlowRole
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流角色管理
	 * @apiParam {WorkFlowRole} entity 工作角色实体
	 * @apiParam {String} roleName 角色名称
	 * @apiParam {String} key 键
	 * @apiParam {String} remark 描述
	 * @apiParamExample {json} 请求参数示例
	 *                  {"roleName":"信用中信","key":"xyzx","remark":"信用中信"}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/addWorkFlowRole", method = RequestMethod.POST)
	public RestServiceResult<Object> addWorkFlowRole(@RequestBody WorkFlowRole entity) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entity) {
			try {
				workFlowRoleService.addWorkFlowRole(entity);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("添加失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}

	/**
	 * @api {post} /wfrole/queryWorkFlowRoleForPage.json 分页查询工作角色列表
	 * @apiName queryWorkFlowRoleForPage
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流角色管理
	 * @apiParam {int} page 当前页码
	 * @apiParam {int} limit 每页条数
	 * @apiParam {String} roleName 角色名称
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {long} id 角色Id
	 * @apiSuccess {String} roleName 角色名称
	 * @apiSuccess {String} key 键
	 * @apiSuccess {String} remark 描述
	 * @apiSuccess {long} createTime 创建时间
	 * @apiSuccessExample {json} 成功返回结果 {"code":0,"msg":"","count":1,"data":
	 *                    [{"id":2,"createTime":1531364261000,"roleName":"科长1","remark":"科长","key":"kezhang"}]}
	 */
	@RequestMapping(value = "/queryWorkFlowRoleForPage", method = RequestMethod.POST)
	public RestServiceResult<List<WorkFlowRole>> queryWorkFlowRoleForPage(int page, int limit, String roleName) {
		Map<String, Object> params = new HashMap<>();
		Page pager = super.getPage(page, limit);
		params.put("page", pager);
		params.put("roleName", roleName);
		List<WorkFlowRole> datas = workFlowRoleService.queryWorkFlowRoleForPage(params);
		return super.getPageSuccessRestServiceResult(pager.getTotalCount(), datas);
	}

	/**
	 * @api {post} /wfrole/findOneWorkFlowRole.json 根据区域Id获取工作角色信息
	 * @apiName findOneWorkFlowRole
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流角色管理
	 * @apiParam {long} id 工作角色Id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {long} id 角色Id
	 * @apiSuccess {String} roleName 角色名称
	 * @apiSuccess {String} key 键
	 * @apiSuccess {String} remark 描述
	 * @apiSuccess {long} createTime 创建时间
	 * @apiSuccessExample {json} 成功返回结果 {"code":0,"msg":"","count":1,"data":
	 *                    {"id":2,"createTime":1531364261000,"roleName":"科长1","remark":"科长","key":"kezhang"}}
	 */
	@RequestMapping(value = "/findOneWorkFlowRole", method = RequestMethod.POST)
	public RestServiceResult<WorkFlowRole> findOneWorkFlowRole(long id) {
		WorkFlowRole data = null;
		if (id > Constants.NUMBER_ZERO) {
			data = workFlowRoleService.findOneWorkFlowRole(id);
		}
		return super.getSuccessRestServiceResult(data);
	}

	/**
	 * @api {post} /wfrole/getAllWorkFlowRoles.json 获取所有工作流角色数据
	 * @apiName getAllWorkFlowRoles
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流角色管理
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {long} id 角色Id
	 * @apiSuccess {String} roleName 角色名称
	 * @apiSuccess {String} key 键
	 * @apiSuccess {String} remark 描述
	 * @apiSuccess {long} createTime 创建时间
	 * @apiSuccessExample {json} 成功返回结果 {"code":0,"msg":"","count":1,"data":
	 *                    [{"id":2,"createTime":1531364261000,"roleName":"科长1","remark":"科长","key":"kezhang"}]}
	 */
	@RequestMapping(value = "/getAllWorkFlowRoles", method = RequestMethod.POST)
	public RestServiceResult<List<WorkFlowRole>> getAllWorkFlowRoles() {
		List<WorkFlowRole> datas = null;
		datas = workFlowRoleService.getAllWorkFlowRoles();
		return super.getSuccessRestServiceResult(datas);
	}

	/**
	 * @api {post} /wfrole/updateWorkFlowRole.json 更新工作角色信息
	 * @apiName updateWorkFlowRole
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流角色管理
	 * @apiParam {WorkFlowRole} entity 工作角色实体
	 * @apiParam {String} roleName 角色名称
	 * @apiParam {String} key 键
	 * @apiParam {String} remark 描述
	 * @apiParam {long} id 角色Id
	 * @apiParamExample {json} 请求参数示例
	 *                  {"roleName":"信用中信","key":"xyzx","remark":"信用中信","id":10}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/updateWorkFlowRole", method = RequestMethod.POST)
	public RestServiceResult<Object> updateWorkFlowRole(@RequestBody WorkFlowRole entity) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entity) {
			try {
				workFlowRoleService.updateWorkFlowRole(entity);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("更新失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}

	/**
	 * @api {post} /wfrole/getUserWFRole.json 获取用户工作流角色
	 * @apiName getUserWFRole
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流角色管理
	 * @apiParam {long} userId 用户Id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {long} id 角色Id
	 * @apiSuccess {long} userId 用户Id
	 * @apiSuccessExample {json} 成功返回结果 {"code":0,"msg":"","count":1,"data":
	 *                    [{"id":2,"userId":101}]}
	 */
	@RequestMapping(value = "/getUserWFRole", method = RequestMethod.POST)
	public RestServiceResult<List<WorkFlowRole>> getUserWFRole(long userId) {
		List<WorkFlowRole> data = null;
		if (userId > Constants.NUMBER_ZERO) {
			data = workFlowRoleService.getUserWFRole(userId);
		}
		return super.getSuccessRestServiceResult(data);
	}

	/**
	 * @api {post} /wfrole/modifyWFRoleUser.json 更新工作角色与用户信息
	 * @apiName modifyWFRoleUser
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流角色管理
	 * @apiParam {WorkFlowRole} entity 实例对象
	 * @apiParam {long} id 角色Id
	 * @apiParam {long} userId 用户Id
	 * @apiParamExample {json} 请求参数示例 {"id":2,"userId":101}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/modifyWFRoleUser", method = RequestMethod.POST)
	public RestServiceResult<Object> modifyWFRoleUser(@RequestBody List<WorkFlowRole> entities,
			HttpServletRequest request) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entities) {

			try {
				UserEntity user = authenticationService.getCurrentUserInfo(HttpServletHelper.getUserToken(request));
				if (null != user && user.getId() > Constants.NUMBER_ZERO && 1 == user.getUserType()) {
					// 普通用户无法创建用户
					return super.getFailedRestServiceResult("你无此权限，不能使用此功能，请联系管理员");
				}
				workFlowRoleService.modifyWFRoleUser(entities);

			} catch (Exception e) {
				result = super.getFailedRestServiceResult("更新失败！");
				ExceptionLogger.error(e);
			}

		}
		return result;
	}

	/**
	 * @api {post} /wfrole/batchDelWorkFlowRole.json 批量删除工作角色
	 * @apiName batchDelWorkFlowRole
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流角色管理
	 * @apiParam {String} ids 工作角色Id集合
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/batchDelWorkFlowRole", method = RequestMethod.POST)
	public RestServiceResult<Object> batchDelWorkFlowRole(String ids) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (StringUtils.isNotBlank(ids)) {
			try {
				workFlowRoleService.batchDelWorkFlowRole(super.convert2Long(ids));
			} catch (ServiceException e) {
				result = super.getFailedRestServiceResult(e.getMessage());
				ExceptionLogger.error(e);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("删除失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}

	/**
	 * @api {post} /wfrole/isExistWorkFlowRole.json 判断是否有重复数据
	 * @apiName isExistWorkFlowRole
	 * @apiVersion 0.0.1
	 * @apiGroup 工作流角色管理
	 * @apiParam {String} roleName 角色名称
	 * @apiParam {String} key 键
	 * @apiParam {long} id 角色Id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} flag true 存在重复, false 不存在重复
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":{"flag":"false"}}
	 */
	@RequestMapping(value = "/isExistWorkFlowRole", method = RequestMethod.POST)
	public RestServiceResult<Map<String, String>> isExistWorkFlowRole(String roleName, String key,
			@RequestParam(value = "id", required = false, defaultValue = "0") long id) {
		RestServiceResult<Map<String, String>> rstData = null;
		Map<String, String> result = new HashMap<>();
		String flag = "";
		try {
			Map<String, Object> params = new HashMap<>();
			params.put("roleName", roleName);
			params.put("key", key);
			params.put("id", id);
			List<WorkFlowRole> datas = workFlowRoleService.isExistWorkFlowRole(params);
			if (!CollectionUtils.isEmpty(datas)) {
				flag = "true";
			} else {
				flag = "false";
			}
			result.put("flag", flag);
		} catch (Exception e) {
			rstData = super.getFailedRestServiceResult("查询失败！");
			ExceptionLogger.error(e);
		}
		rstData = super.getSuccessRestServiceResult(result);
		return rstData;
	}
}